#! /bin/bash

version=$1

if [ -n "$DEB_MAINT_PARAMS" ]; then
    eval set -- "$DEB_MAINT_PARAMS"
    if [ -z "$1" ] || [ "$1" != "configure" ]; then
        exit 0;
    fi
fi

architecture=$(dpkg --print-installation-architecture)

case $architecture in
    powerpc)
        architecture='ppc'
        ;;
    hppa)
        architecture='parisc'
        ;;
    mipsel)
        architecture='mips'
        ;;
    amd64|i386)
        architecture='x86'
        ;;
    *)
        :
esac

# passing the kernel version is required
[ -z "$version" ] && exit 1

MODULEDIR=/lib/modules/$version
HEADERDIR=/usr/src/linux-headers-$version

test -d $HEADERDIR || exit 0


# See if we have a kernel image of the same version already
# installed.
if  [ -d "$MODULEDIR"  ] &&
    [ ! -e "$MODULEDIR/build" ]; then
    if ! ln -s "$HEADERDIR"  "$MODULEDIR/build" ; then
        echo >&2 "Could not link $HEADERDIR to $MODULEDIR/build";
    fi
fi

# Make sure the asm link is sane
if [ ! -d "$HEADERDIR/include" ]; then
    echo >&2 "$HEADERDIR/include does not exist"
    exit 1
fi
cd "$HEADERDIR/include"
if [ ! -s "asm-$architecture" ]; then
    echo >&2 "$HEADERDIR/include/asm-$architecture does not exist"
elif [ -e 'asm' ]; then
    if [ ! -L 'asm' ]; then
        echo >&2 "$HEADERDIR/include/asm is not a symbolic link"
    else
        rm -f asm
        ln -sf  "asm-$architecture" 'asm'
    fi
fi    

exit 0
